// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// o [author] rhyme_lph
// S [email]  rhymelph@gmail.com
// O [github] https://github.com/rhymelph

import 'dart:async';

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/src/entities/tag_entity.dart';
import 'package:finance_app/src/http_service/http_common_service.dart';
import 'package:flutter/material.dart';

class ProductsAndServicesCategoryProvider extends BaseProvider {
  List<String> widgetData = [''];
  List<TextEditingController> controllers;
  List<FocusNode> focusNodes;

  List<TagEntity> tags = [];
  String type;

  @override
  Future get dataFuture => null;

  @override
  void initState() {
    super.initState();
    _loadCategory();
  }

  void initWidgetData(String type, List<String> categories) {
    this.type = type;
    widgetData = categories == null ? [''] : categories;
    controllers =
        widgetData.map((e) => TextEditingController(text: e)).toList();
    focusNodes = widgetData.map((e) => FocusNode()).toList();
  }

  void unFocus() {
    focusNodes.forEach((element) {
      element.unfocus();
    });
  }

  void onAddCategory() {
    unFocus();
    controllers.add(TextEditingController(text: ''));
    focusNodes.add(FocusNode());
    update();
  }

  @override
  void dispose() {
    super.dispose();
    controllers.forEach((element) {
      element.dispose();
    });
    focusNodes.forEach((element) {
      element.dispose();
    });
  }

  void onDone() {
    obtainContext?.call((context) {
      Navigator.of(context).pop(controllers
          .where((element) => element.text.trim().isNotEmpty)
          .map((e) => e.text)
          .toList());
    });
  }

  void onRemove(int value) {
    if (controllers.length == 1) {
      controllers[0].clear();
      return;
    }
    TextEditingController controller = controllers.removeAt(value);
    FocusNode node = focusNodes.removeAt(value);
    Timer(Duration(milliseconds: 1000), () {
      controller.dispose();
      node.dispose();
    });
    update();
  }

  void _loadCategory() async {
    await post(HttpCommonService.getTags(type), autoHandler: AutoHandler.Toast,
        onSuccess: (result) {
      tags = getEntityFromResult<List<TagEntity>>(result);
      update();
    });
  }
}
